<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/10/18
 * Time: 14:52
 */
class Customer extends CI_Controller{
    public function __construct(){
        parent::__construct();
        $this->load->model("customer_model");
    }

    /*
     * 人物关系管理
     * */
    public function index($cardId=101){
        $this->load->view('admin/common/header');
        $data =  array("cardId" =>$cardId);
        $this->load->view('admin/customer/customer',$data);
    }


    public function get_customer_limit_json($condition="")
    {
        $page 	= isset($_POST['page']) ? intval($_POST['page']) : 1;
        $rows 	= isset($_POST['rows']) ? intval($_POST['rows']) : 20;
        $sort 	= isset($_POST['sort']) ? strval($_POST['sort']) : "a.id";
        $order 	= isset($_POST['order']) ? strval($_POST['order']) : 'desc';
        $offset = ($page-1)*$rows;
        $result 	= $this->customer_model->get_customer_array_limit($offset,$rows,$sort,$order,$condition);
        $total 		= $this->customer_model->get_customer_rows($condition);
        $arr 		= array(
            "total"=> $total,
            "rows" => $result
        );

        $json_str = json_encode($arr);
        echo $json_str;
    }

    public function import(){
        $this->load->view('admin/common/header_s');
        $data =  array();
        $this->load->view('admin/customer/import',$data);
    }
    public function uploads(){
        $config['upload_path']      = './uploads/temp';
        $config['allowed_types']    = 'xls|xlsx|csv';
        $config['file_name']        = uuid();
        $config['max_size']         = 1024*10;//尺寸kb
        $this->load->library('upload', $config);

        if ( ! $this->upload->do_upload('file'))
        {
            $error = $this->upload->display_errors();
            json_return('error',$error);
        }
        else
        {
            $d=$this->upload->data();
            $filepath  =  $config['upload_path'].'/'.$d['file_name'];
            $result  = $this->importExcel($filepath);
            if($result =="ok"){
                $status = 1;
                $msg    = "成功";
            }else{
                $status =-1;
                $msg    = "失败";
            }
            $arr     = array("status"=>$status,"msg"=>$msg);
            $json_str = json_encode($arr);
            echo $json_str;
        }
    }


    public function importExcel($filepath=0) {
        //$filepath   = "./uploads/excel/F80-2015-12-0593.xlsx";
        $file       = pathinfo($filepath);
        $this->load->library('Classes/PHPExcel.php');

        $inputFileType = PHPExcel_IOFactory::identify($filepath);
        $objReader = PHPExcel_IOFactory::createReader($inputFileType);

        $objPHPExcel    = $objReader->load($filepath);
        $objWorksheet   = $objPHPExcel->getSheet(0)->toArray();


        unset($objWorksheet[0]);
        unset($objWorksheet[1]);
        $i = 0;
        $litigant_cardId =""; // 当事人
        foreach($objWorksheet  as $row) {
            if ($row[2] == "" && $row[7] == "") {
                continue;
            }

            $sourcedata = array(
                "name" => $row[0],
                "oldname" => $row[1],
                "lable" => $row[0],
                "cardId" => $row[2],
                "is_dead" => $row[3],
                "dead_time" => mb_convert_encoding($row[4], "UTF-8", "auto")
            );


            $targetdata = array(
                "name" => $row[5],
                "oldname" => $row[6],
                "lable" => $row[5],
                "cardId" => $row[7],
                "is_dead" => $row[8],
                "dead_time" => mb_convert_encoding($row[9], "UTF-8", "auto")
            );

            $source_link    = 0;
            $source_id      = 0;
            if ($row[2] != "") {
                $condition = array("cardId" => $row[2]);
                $source_arr = $this->table_model->get_array_one("customer", $condition);
                if (empty($source_arr)) {
                    $source_id = $this->table_model->add("customer", $sourcedata);
                } else {
                    $condition = array("id" => $source_arr["id"]);
                    $source = $this->table_model->save("customer", $condition, $sourcedata);
                    $source_id = $source_arr["id"];
                }
            }
            $target_id = 0;
            $target_link    = 0;
            if ($row[7] != "") {
                $condition = array("cardId" => $row[7]);
                $target_arr = $this->table_model->get_array_one("customer", $condition);

                if (empty($target_arr)) {
                    $target_id = $this->table_model->add("customer", $targetdata);
                } else {
                    $condition = array("id" => $target_arr["id"]);
                    $target = $this->table_model->save("customer", $condition, $targetdata);
                    $target_id = $target_arr["id"];
                }
            }

            if ($row[2] != "" && $row[7] != "" ) {
                $condition = array("new_number"=>$file["filename"]);
                $archive = $this->table_model->get_array_one("archive",$condition);
                if($archive){
                    $archive_id = $archive["id"];
                }else{
                    $archive_id = 0;
                }
                $sourcelinkdata = array(
                    "source"            => $row[2],
                    "target"            => $row[7],
                    "name"              => $row[10],
                    "relation_stop"    => mb_convert_encoding($row[11], "UTF-8", "auto"),
                    "archive_id"        => $archive_id,     //案卷号
                    "archive_number"    => $file["filename"]     //案卷号
                );
                /*
                $targetlinkdata = array(
                    "source"    => $row[7],
                    "target"    => $row[2],
                    "name"      => $row["10"],
                    "releation_stop" => $row["11"]
                );
                */
                $condition = array("source" => $row[2], "target" => $row[7]);
                $link = $this->table_model->get_array_one("customer_links", $condition);
                if (empty($link)) {
                    $id = $this->table_model->add("customer_links", $sourcelinkdata);
                } else {
                    $target = $this->table_model->save("customer_links", $condition, $sourcelinkdata);
                }

                /*
                $condition = array("source" => $row[7], "target" => $row[2]);
                $link = $this->table_model->get_array_one("customer_links", $condition);
                if (empty($link)) {
                    $id = $this->table_model->add("customer_links", $targetlinkdata);
                } else {
                    $target = $this->table_model->save("customer_links", $condition, $targetlinkdata);
                }
                */
            }
        }

        return  "ok";

    }



    function getCall($name="弟") {

        $call    = $this->table_model->get_array("customer_call", "");
        $backname = $name."(反向称呼)";
        foreach($call  as $row){
            if($name  == $row["name"]){
                $backname = $row["backname"];
                break;
            }else if($name  == $row["backname"]){
                $backname  = $row["name"];
                break;
            }
        }
       return  $backname;
    }



    function batch_import()
    {

        $mainfile           = "./uploads/excel/main.php";
        $workfile           = "./uploads/excel/work.php";
        $xls_filepath       = "./uploads/excel/import";
        $result             = $this->getDir($xls_filepath);
        $main               = array("total"=>count($result));

        $str                = "<?php \n return ".var_export($main,TRUE).";\n?>";
        file_put_contents($mainfile, $str);
        $str                = "<?php \n return ".var_export($result,TRUE).";\n?>";
        file_put_contents($workfile, $str);

        $data['action_url']	= site_url("/admin/customer/work");
        $this->load->view('admin/customer/progressbar',$data);
    }

    function work()
    {
        $main_file  = "./uploads/excel/main.php";
        $work_file  = "./uploads/excel/work.php";
        $xls_file   = "./uploads/excel/import";
        $main       = include_once($main_file);
        $work       = include_once($work_file);
        sleep(1);
        if (empty($work)) {
            echo '<script>parent.show_bar(100);</script>';
        } else {
            $total              = $main["total"];
            $currentfile        = $xls_file."/".current($work);
            $this->importExcel($currentfile);
            $new = array_shift($work);
            $buffer = ini_get('output_buffering');
            echo str_repeat(' ',$buffer+1); //防止浏览器缓存
            $percent = ceil((($total-count($work))/$total)*100);
            echo '<script>parent.show_bar('.$percent.');</script>';
            unlink($currentfile);
            file_put_contents($work_file, "<?php \n return " . var_export($work, TRUE) . ";\n?>");
            $url  = site_url("/admin/customer/work");
            echo "<script>location.href='".$url."'</script>";
            exit;
        }
    }


    public function show_progressbar($percent)
    {
        echo '<script>parent.show_bar('.$percent.');</script>';
    }
    /**
     * @param string $dir
     * @return array
     */
    function getDir($dir="")
    {

        $files = array();
        if ( $handle = opendir($dir) ) {
            while ( ($file = readdir($handle)) !== false )
            {
                if ( $file != ".." && $file != "." )
                {
                    if ( is_dir($dir . "/" . $file) )
                    {
                        $files[$file] = $this->getDir($dir . "/" . $file);
                    }
                    else
                    {
                        $files[] = $file;
                    }
                }
            }
            closedir($handle);
            return $files;
        }
    }


}